'use strict';
app.config(['calendarConfigProvider', function(calendarConfigProvider) {
    calendarConfigProvider.setDateFormatter('moment'); // use moment to format dates
    calendarConfigProvider.setTitleFormats({
        day: 'dddd MMMM DD, YYYY',
        week: '{year}年{week}周',
        month: 'MMMM YYYY',
        year: 'YYYY'
            //day: 'ddd D MMM' //this will configure the day view title to be shorter
    });

    calendarConfigProvider.setI18nStrings({
        eventsLabel: '描述', //This will set the events label on the day view
        timeLabel: '时间', //This will set the time label on the time view
        weekNumber: '{week}周'
    });
}]);

/**
 * Controller of the angularBootstrapCalendarApp
 */
app.controller('schedulingCtrl', ["$scope", "i18nService", "$rootScope", "$log", "$state", "$timeout", "$interval", "SweetAlert", 'FileUploader', "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_bpm_domain", "api_bpm_data", "$aside", "moment", function($scope, i18nService, $rootScope, $log, $state, $timeout, $interval, SweetAlert, FileUploader, uiGridConstants, uiGridGroupingConstants, Restangular, api_bpm_domain, api_bpm_data, $aside, moment) {
    var loginUser = $rootScope.user;
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    i18nService.setCurrentLang($scope.lang);
    $scope.allright = false;
    $scope.someright = true;
    for (var obj in $rootScope.user.role) {
        if ($rootScope.user.role[obj].rolecode == 'schedule manager') {
            $scope.allright = true;
            $scope.someright = false;
        }
    }
    var pdKey = $state.current.pdKey;

    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = false;
    $scope.gridOptions.enableGridMenu = true;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = true;
    $scope.gridOptions.fastWatch = true;
    // $scope.gridOptions.useExternalFiltering=true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = false;

    $scope.gridOptions.rowTemplate = "<div ng-dblclick=\"grid.appScope.pdList.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };

    $scope.gridOptions.columnDefs = [{
        name: '操作',
        cellTemplate: '<schedulingoperator item="row.entity" colobject="col">',
        width: 100,
        enableFiltering: false
    }, {
        name: 'sourceWatch.watchTime',
        displayName: '换班时间',
        width: 120,
        enableFiltering: false
    }, {
        name: 'initUser.name',
        displayName: '申请人',
        width: 140,
        enableFiltering: false
    }, {
        name: 'sourceWatch.scheduleClass.name',
        displayName: '换班班次',
        width: 100,
        enableFiltering: false
    }, {
        name: 'endWatch.watchTime',
        displayName: '对换时间',
        width: 120,
        enableFiltering: false
    }, {
        name: 'endWatch.user.name',
        displayName: '对换人员',
        width: 120,
        enableFiltering: false
    }, {
        name: 'endWatch.scheduleClass.name',
        displayName: '对换班次',
        width: 140,
        enableFiltering: false
    }, {
        name: 'stage.name',
        displayName: '状态',
        width: 120,
        enableFiltering: false
    }];

    // $scope.gridOptions.importerDataAddCallback = function( grid, newObjects ) {
    //   $scope.myData = $scope.myData.concat( newObjects );
    //     console.log($scope);
    // };

    $scope.refresh = function(style, filterData) {
        var filtersData = {
            "assignee": $rootScope.user.id,
            "candidateGroups": $rootScope.user.group[0].id,
            idx: 0,
            sum: 10
        };
        $scope.gridOptions.refresh();
        $scope.refreshData('expand-right', filtersData);
    };

    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            // console.log(newPage);
            // console.log(pageSize);
            $rootScope['idx'] = newPage;
            $scope.refreshData('expand-right', {
                "assignee": $rootScope.user.id,
                // "candidateGroups":$rootScope.user.group[0].id,
                "idx": newPage - 1,
                "sum": pageSize
            });
        });
        //         gridApi.core.on.filterChanged($scope, function() {
        //             var grid = this.grid;
        //             var filtersData = {
        //             "assignee":$rootScope.user.id,
        //             "candidateGroups":$rootScope.user.group[0].id,
        //             "idx":0,
        //             "sum":10
        //         };
        //         angular.forEach(grid.columns,function(item){
        //         if(item.enableFiltering){
        //         if(angular.isDefined(item.filters[0].term)&&item.filters[0].term!=''){
        //         // console.log('item.filters[0]='+JSON.stringify(item.filters[0]));
        //             if(angular.isUndefined(filtersData['scheduling'])){
        //                 filtersData['scheduling']={};
        //             }
        //             filtersData['scheduling'][item.field]=item.filters[0].term;
        //         }                                                
        //     }
        //   });
        //   $scope.refreshData('expand-right', filtersData);
        // });
        // gridApi.selection.on.rowSelectionChanged($scope, function(data) {
        //     //$scope.selected.item = data.entity;
        //     console.log(data);
        // });
    };
    // $scope.gridOptions.appScopeProvider = { 
    //         onDblClick : function(row) {
    //             $state.go('app.form.detail',{data:row, formKey:'changeDetail', pdKey:'change'});
    //             //var url = '//google.com';
    //             //$window.open(url, "_blank", "height=600,width=800,toolbar=no,location=no,menubar=no,titlebar=no");
    //         }
    // };

    $scope.selectRowFunction = function(data) {
        console.log(data);
        //    $state.go('app.process.modeler',{modelId:data.id});
        $state.go('app.scheduling.editor', {
            taskId: data.taskId,
            processInstanceId: data.processInstanceId
        });
    };
    $scope.lookfunction = function(data) {
        //console.log(row.entity);
        $state.go('app.detail', { formKey: 'schedulingDetail', pdKey: 'schedule', dataId: data.id, taskId: data.taskId, processInstanceId: data.processInstanceId });
    };
    $scope.onDblClick = function(row) {
        //console.log(row.entity);
        $state.go('app.detail', { formKey: 'schedulingDetail', pdKey: 'schedule', dataId: row.entity.id, taskId: row.entity.taskId, processInstanceId: row.entity.processInstanceId });
    };
    // this.onDblClick = function(row) {
    //     //console.log(row.entity);
    //     $state.go('app.detail', {
    //         formKey: 'schedulingDetail',
    //         pdKey: 'scheduling',
    //         dataId: row.entity.id
    //     });
    // };

    /*
    appScopeProvider: { 
        onDblClick : function(row) {
           var url = '//google.com';
           $window.open(url, "_blank", "height=600,width=800,toolbar=no,location=no,menubar=no,titlebar=no");
         }
    },
    rowTemplate: "<div ng-dblclick=\"grid.appScope.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" ui-grid-cell ></div>"

   */

    this.removeRowFunction = function(data) {
        //TODO $translate('key')
        SweetAlert.swal({
            title: "确认删除?",
            text: "删除以后，你将不能恢复该数据!",
            type: "warning",
            cancelButtonText: "取消",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认删除!"
        }, function(isConfirm) {
            if (isConfirm) {
                // api_bpm_domain.removemodel(data.id).then(function(response){
                //   if(response){
                //     $scope.refreshData();
                //     SweetAlert.swal({
                //       title: "删除成功!",
                //       confirmButtonColor: "#007AFF"
                //     });
                //   }
                // });
            } else {

            }
        });

    }


    //$scope.callsPending = 0;
    //var i = 0;
    var defaultFilterData = {
        "assignee": $rootScope.user.id,
        // "candidateGroups":$rootScope.user.group[0].id,
        "idx": 0,
        "sum": 10
    };
    if (angular.isDefined($rootScope.search) && angular.isDefined($rootScope.search.scheduling)) {
        defaultFilterData['searchType'] = $rootScope.search.scheduling;
        $scope.searchTypes = $rootScope.search.scheduling;
    }
    if ($rootScope['cmdbs'] != 'scheduling') { $rootScope.idx = 1 }
    if (angular.isDefined($rootScope.idx) && $rootScope.cmdbs != "false") {
        $rootScope['cmdbs'] = 'scheduling';
        defaultFilterData.idx = $rootScope.idx - 1;
    } else { $rootScope.cmdbs = ""; }
    $scope.ldloading = {};
    $scope.refreshData = function(style, filterData) {
        $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            defaultFilterData.idx = $rootScope.idx - 1;
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            $rootScope['search'] = {};
            filterData['searchType'] = $scope.searchTypes;
            $rootScope['search']['scheduling'] = $scope.searchTypes;
        }


        $scope.myData = [];
        //var start = new Date();
        //var sec = $interval(function () {
        //$scope.callsPending++;
        api_bpm_domain.fetchtask(pdKey, filterData).then(function(data) {
            $scope.callsPending--;
            // console.log('filterData='+JSON.stringify(filterData));
            var myData = Restangular.stripRestangular(data);
            $scope.gridOptions.totalItems = myData.resultCount;
            $scope.myData = myData.data;
            $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            $scope.ldloading[style.replace('-', '_')] = false;
        });
    };

    $scope.refreshData('expand-right', defaultFilterData);

}]);
app.controller('SchedulingOperCtrl', ['$rootScope', '$http', '$scope', function($rootScope, $http, $scope, $event) {
    if ($scope.item.handlerUser != null) {

        if ($rootScope.user.id == $scope.item.handlerUser.id) {
            $scope.item.chaozuoPower = true;

        }
    }

    $scope.look = function() {
        $scope.colobject.grid.appScope.lookfunction($scope.item);

    }
    $scope.edit = function() {
        $scope.colobject.grid.appScope.selectRowFunction($scope.item);
        // console.log('$scope.item='+JSON.stringify($scope.item));
        $scope.doEdit($scope.item.id);
    }



}]);

app.directive('schedulingoperator', function() {
    return {
        restrict: 'E',
        scope: {
            item: '=',
            colobject: '='
        },
        controller: 'SchedulingOperCtrl',
        template: '<div class="links cl-effect-1 ui-grid-cell-contents">' +
            '<a ng-click="look()"   tooltip="查看" tooltip-placement="right"><i class="ti-eye"></i></a>' +
            '<a ng-click="edit()"  ng-show="{{item.chaozuoPower}}"  tooltip="编辑" tooltip-placement="right"><i class="fa fa-pencil-square-o"></i></a>' +
            '</div>'
    };
});



app.controller('myCalendarCtrl', ["$rootScope", "$scope", "$aside", "calendarConfig", "moment", "SweetAlert", "Restangular", "api_bpm_schedule", "api_user_data", function($rootScope, $scope, $aside, calendarConfig, moment, SweetAlert, Restangular, api_bpm_schedule, api_user_data) {
    var loginUser = $rootScope.user;
    //console.log(loginUser);
    calendarConfig.dateFormatter = 'moment';
    calendarConfig.i18nStrings.eventsLabel = '排班描述';
    calendarConfig.i18nStrings.timeLabel = '时间';
    calendarConfig.i18nStrings.weekNumber = '{week}周';

    calendarConfig.allDateFormats = {
        angular: {
            date: {
                hour: 'ha',
                day: 'd MMM',
                month: 'MMMM',
                weekDay: 'EEEE',
                time: 'HH:mm',
                datetime: 'MMM d, h:mm a'
            },
            title: {
                day: 'yyyy MMMM EEEE d',
                week: '{year}年第{week}周',
                month: 'yyyy MMMM',
                year: 'yyyy'
            }
        },
        moment: {
            date: {
                hour: 'ha',
                day: 'MMMDD日',
                month: 'MMMM',
                weekDay: 'dddd',
                time: 'HH:mm',
                datetime: 'MMM D, h:mm a'
            },
            title: {
                day: 'YYYY年MMMMDD日, dddd ',
                week: '{year}年第{week}周',
                month: 'YYYY年MMMM',
                year: 'YYYY'
            }
        }
    };

    moment.locale('zh_cn', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'Ah点mm分',
            LTS: 'Ah点m分s秒',
            L: 'YYYY-MM-DD',
            LL: 'YYYY年MMMD日',
            LLL: 'YYYY年MMMD日Ah点mm分',
            LLLL: 'YYYY年MMMD日ddddAh点mm分',
            l: 'YYYY-MM-DD',
            ll: 'YYYY年MMMD日',
            lll: 'YYYY年MMMD日Ah点mm分',
            llll: 'YYYY年MMMD日ddddAh点mm分'
        },
        meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
        meridiemHour: function(hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' ||
                meridiem === '上午') {
                return hour;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            } else {
                // '中午'
                return hour >= 11 ? hour : hour + 12;
            }
        },
        meridiem: function(hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return '凌晨';
            } else if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: function() {
                return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
            },
            nextDay: function() {
                return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
            },
            lastDay: function() {
                return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
            },
            nextWeek: function() {
                var startOfWeek, prefix;
                startOfWeek = moment().startOf('week');
                prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]';
                return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
            },
            lastWeek: function() {
                var startOfWeek, prefix;
                startOfWeek = moment().startOf('week');
                prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]';
                return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
            },
            sameElse: 'LL'
        },
        ordinalParse: /\d{1,2}(日|月|周)/,
        ordinal: function(number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '周';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            m: '1 分钟',
            mm: '%d 分钟',
            h: '1 小时',
            hh: '%d 小时',
            d: '1 天',
            dd: '%d 天',
            M: '1 个月',
            MM: '%d 个月',
            y: '1 年',
            yy: '%d 年'
        },
        week: {
            // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });
    //console.log(window.moment().weekdays);

    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    console.log(loginUser);
    var filterData = {
        "userId": loginUser.id,
        "startTime": moment(new Date(y, m, 1, 0, 0)).format('YYYY-MM-DD HH:mm:ss'),
        "endTime": moment(new Date(y, m + 1, 1, 0, 0)).format('YYYY-MM-DD HH:mm:ss')
    };
    var load = $scope.load = function(filterData) {
        api_bpm_schedule.fetchSchedule(filterData.userId, filterData.startTime, filterData.endTime).then(function(response) {
            if (response.status == 200) {
                $scope.events = [];
                console.log(response.list);
                var myData = response.list;


                angular.forEach(myData, function(item) {
                    var eventTemp = {};
                    eventTemp.title = item.description;
                    eventTemp.type = item.scheduleClass.code;
                    eventTemp.startsAt = moment(item['scheduleOrderDTO'].startTime).toDate();
                    eventTemp.endsAtTime = moment(item['scheduleOrderDTO'].endTime).toDate();
                    eventTemp.startTime = item['scheduleOrderDTO'].startTime;
                    eventTemp.endTime = item['scheduleOrderDTO'].endTime;
                    //eventTemp.ends_at = moment(item.endTime).toDate();
                    eventTemp.id = item.id;
                    eventTemp.deletable = false;
                    eventTemp.user = item.user;
                    $scope.events.push(eventTemp);
                })
            }
        });
    }

    // var load = $scope.load = function(filterData){
    //     api_bpm_schedule.fetchSchedule(filterData.userId, filterData.startTime, filterData.endTime).then(function(response){
    //         console.log("response="+JSON.stringify(response));
    //         if(response.status==200){
    //             $scope.events = [];
    //             console.log(response.list);
    //             var myData = response.list;
    //             angular.forEach(myData,function(item){
    //                 var eventTemp = {};
    //                 eventTemp.title = item.description;
    //                 eventTemp.type = item.scheduleClass.code;
    //                 eventTemp.startsAt = moment(item.startTime).toDate();
    //                 eventTemp.endsAtTime = moment(item.endTime).toDate();
    //                 eventTemp.startTime = item.startTime;
    //                 eventTemp.endTime = item.endTime;
    //                 //eventTemp.ends_at = moment(item.endTime).toDate();
    //                 eventTemp.id = item.id;
    //                 eventTemp.deletable = false;
    //                 eventTemp.users = item.users;
    //                 $scope.events.push(eventTemp);
    //                 // console.log("eventTemp="+JSON.stringify(eventTemp));
    //             })
    //         }
    //     });     
    // }


    $scope.scheduleClass = {};
    var convertEvent = function(scheduleorder) {
        var eventTemp = {};
        eventTemp.title = scheduleorder.description;
        eventTemp.type = scheduleorder.scheduleClass.code;
        eventTemp.startsAt = moment(scheduleorder.startTime).toDate();
        //eventTemp.ends_at = moment(scheduleorder.endTime).toDate();
        eventTemp.id = scheduleorder.id;
        eventTemp.user = scheduleorder.user;
        eventTemp.deletable = false;
        return eventTemp;
    }


    // var convertEvent = function(scheduleorder){
    //     var eventTemp = {};
    //     eventTemp.title = scheduleorder.description;
    //     eventTemp.type = scheduleorder.scheduleClass.code;
    //     eventTemp.starts_at = moment(scheduleorder.scheduleClass.startTime).toDate();
    //     eventTemp.ends_at = moment(scheduleorder.scheduleClass.endTime).toDate();
    //     eventTemp.id = scheduleorder.id;
    //     eventTemp.users = scheduleorder.users;
    //     eventTemp.deletable = false;
    //     return eventTemp;
    // }

    api_bpm_schedule.getScheduleClass().then(function(response) {
        if (response.status == 200) {
            var scheduleClassList = response.list;
            angular.forEach(scheduleClassList, function(item) {
                item.startsAt = moment(item.startTime).format('HH:mm:ss');
                item.endsAt = moment(item.endTime).format('HH:mm:ss');
                // console.log("item.startsAt="+JSON.stringify(item.startsAt))
                // console.log("item.endsAt="+JSON.stringify(item.endsAt))
                $scope.scheduleClass[item['code']] = item;
            })
        }
    })

    $scope.events = [];

    $scope.calendarView = 'month';
    //$scope.calendarDay = new Date();
    $scope.calendarDate = moment().startOf('month').toDate();
    $scope.timeLabel = "时间";
    $scope.eventLabel = "描述";



    function showModal(action, event) {
        // console.log("action="+JSON.stringify(action))
        var modalInstance = $aside.open({
            templateUrl: 'scheduleEvent.html',
            placement: 'right',
            size: 'sm',
            backdrop: true,
            controller: function($scope, $modalInstance, scheduleClass, APIService, MementFormat) {
                $scope.$modalInstance = $modalInstance;
                $scope.action = action;
                $scope.event = event;
                $scope.scheduleClassic = scheduleClass;
                $scope.$watch('event.type', function(newvalue, oldvalue) {
                    // if(oldvalue == newvalue) return;
                    // if(scheduleClass[newvalue]){
                    var sm = MementFormat(scheduleClass[newvalue].startTime);
                    var em = MementFormat(scheduleClass[newvalue].endTime);
                    console.log("sm=" + JSON.stringify(sm))
                    event.starts_at = MementFormat(event.startTime).startOf('day').add(sm.hour(), 'hour').add(sm.minute(), 'minute').add(sm.second(), 'second').toDate();
                    console.log("event.starts_at=" + JSON.stringify(event.starts_at))
                    if (sm.hour() > em.hour()) {
                        event.ends_at = MementFormat(event.startTime).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        console.log("event.ends_at=" + JSON.stringify(event.starts_at))
                    } else {

                        event.ends_at = MementFormat(event.startTime).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        console.log("event.ends_at=" + JSON.stringify(event.ends_at))
                    }

                    // }
                });

                // $scope.ok = function (event) {
                //      console.log("event="+JSON.stringify(event))
                //     event.action = action;
                //     $modalInstance.close(event);
                // };
                $scope.cancel = function(event) {
                    $modalInstance.dismiss();
                };

                var acUserSelect = $scope.refreshUser = function(key) {
                    //for test                  
                    // $scope.users=[{"id":1,"phone":"13971293737","orgId":1,"name":"李静","role":[{"id":1,"rolecode":"admin","role":"主行管理员","flag":0}],"gender":"女","dept":{"id":3,"dept":"运行监控科"},"flag":0,"email":"","account":"005292","nickname":"lijing","group":[{"id":3,"groupName":"运行监控科"}]},{"id":2,"phone":"15807199490","orgId":1,"name":"李进","role":[{"id":1,"rolecode":"admin","role":"主行管理员","flag":0},{"id":7,"rolecode":"change manager","role":"变更流程经理","flag":1},{"id":8,"rolecode":"change coordinator","role":"协调员","flag":0},{"id":9,"rolecode":"configure manager","role":"配置管理员","flag":0},{"id":10,"rolecode":"release manager","role":"发布经理","flag":0}],"gender":"男","dept":{"id":3,"dept":"运行监控科"},"flag":0,"email":"","account":"005298","nickname":"lijin","group":[{"id":3,"groupName":"运行监控科"}]},{"id":3,"phone":"13507195958","orgId":1,"name":"杨代华","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"男","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005241","group":[{"id":9,"groupName":"管理层"}]},{"id":4,"phone":"18717107255","orgId":1,"name":"朱红艳","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"女","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005242","group":[{"id":9,"groupName":"管理层"}]},{"id":5,"phone":"13667282828","orgId":1,"name":"李喆","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"男","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005243","group":[{"id":9,"groupName":"管理层"}]}];
                    // return;
                    var data = { "idx": "0", "sum": "5" };
                    if (key) {
                        data['user'] = {
                            'name': key
                        };
                    }
                    APIService.fetchDataList('user', data).then(function(response) {
                        if (response) {
                            if (response.status = 200) {
                                $scope.users = response.list;
                                console.log($scope.users);
                            }
                        }
                    })
                };

                if (angular.isDefined(event.users) && event.users.length > 0) {

                }
                $scope.users = [event.user];
                acUserSelect();
            },
            resolve: {
                scheduleClass: function() {
                    return $scope.scheduleClass;
                },
                APIService: function() {
                    return api_user_data;
                },
                MementFormat: function() {
                    return moment;
                }
            }
        });
        modalInstance.result.then(function(selectedEvent) {
            if (selectedEvent.action == 'Clicked') {
                // var data = {
                //     "scheduleorder":{
                //         "id":selectedEvent.id,
                //         "description":selectedEvent.title,
                //         "startTime":moment(selectedEvent.starts_at).format('YYYY-MM-DD HH:mm:ss'),
                //         "endTime":moment(selectedEvent.ends_at).format('YYYY-MM-DD HH:mm:ss'),
                //         "users":selectedEvent.users,
                //         "scheduleClass":{"id":$scope.scheduleClass[selectedEvent.type].id}
                //     }
                // };
                // api_bpm_schedule.update(data).then(function(response){
                //     if(response.status==200){
                //         SweetAlert.swal({
                //             title: "操作成功！",
                //             text: "排班更新成功!",
                //             type: "succes"
                //         });
                //         angular.forEach($scope.events,function(item){
                //             if(item.id==selectedEvent.id){
                //                 item = selectedEvent;
                //             }
                //         })
                //     }else{
                //         SweetAlert.swal({
                //             title: "操作失败",
                //             text: "排班更新失败,请稍后重试!",
                //             type: "error"
                //         })
                //     }
                // })
            } else {
                //
            }
        });
    }

    $scope.moment = function(string) {
        return moment(string);
    }


    $scope.eventClicked = function(event) {
        // console.log("event="+JSON.stringify(event))
        showModal('Clicked', event);
    };

    $scope.eventEdited = function(event) {
        showModal('Edited', event);
    };


    var updateView = function(newvalue, oldvalue) {
        if (oldvalue == newvalue) return;
        var timeStart, timeEnd, timeStartSpan, timeEndSpan;

        if ($scope.calendarView == "year") {

        } else if ($scope.calendarView == "month") {
            timeStart = moment(newvalue).startOf('month');
            timeEnd = moment(newvalue).endOf('month');
        } else if ($scope.calendarView == "week") {
            timeStart = moment(newvalue).startOf('week');
            timeEnd = moment(newvalue).endOf('week');

        } else if ($scope.calendarView == "Day") {
            timeStart = moment(newvalue).startOf('day');
            timeEnd = moment(newvalue).endOf('day');
        }
        timeStartSpan = timeStart.format('YYYY-MM-DD HH:mm:ss');
        timeEndSpan = timeEnd.format('YYYY-MM-DD HH:mm:ss');
        filterData["startTime"] = timeStartSpan;
        filterData["endTime"] = timeEndSpan;
        load(filterData);
    }

    $scope.$watch('calendarDate', updateView)


    $scope.next = function() {
        $scope.calendarControl.next();
    }

    $scope.prev = function() {
        $scope.calendarControl.prev();
    }

    $scope.setCalendarToToday = function() {
        $scope.calendarDay = new Date();
    };

    $scope.toggle = function($event, field, event) {
        $event.preventDefault();
        $event.stopPropagation();

        event[field] = !event[field];
    };

    $scope.load(filterData);
}]);

app.controller('adminCalendarCtrl', ["$rootScope", "$scope", "$aside", "calendarConfig", "moment", "SweetAlert", 'FileUploader', "Restangular", "api_bpm_schedule", "api_user_data", "api_bpm_data", function($rootScope, $scope, $aside, calendarConfig, moment, SweetAlert, FileUploader, Restangular, api_bpm_schedule, api_user_data, api_bpm_data) {
    var loginUser = $rootScope.user;
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    // console.log(week);

    calendarConfig.dateFormatter = 'moment';
    calendarConfig.i18nStrings.eventsLabel = '排班描述';
    calendarConfig.i18nStrings.timeLabel = '时间';
    calendarConfig.i18nStrings.weekNumber = '{week}周';

    calendarConfig.allDateFormats = {
        angular: {
            date: {
                hour: 'ha',
                day: 'd MMM',
                month: 'MMMM',
                weekDay: 'EEEE',
                time: 'HH:mm',
                datetime: 'MMM d, h:mm a'
            },
            title: {
                day: 'yyyy MMMM EEEE d',
                week: '{year}年第{week}周',
                month: 'yyyy MMMM',
                year: 'yyyy'
            }
        },
        moment: {
            date: {
                hour: 'ha',
                day: 'MMMDD日',
                month: 'MMMM',
                weekDay: 'dddd',
                time: 'HH:mm',
                datetime: 'MMM D, h:mm a'
            },
            title: {
                day: 'YYYY年MMMMDD日, dddd ',
                week: '{year}年第{week}周',
                month: 'YYYY年MMMM',
                year: 'YYYY'
            }
        }
    };

    moment.locale('zh_cn', {
        months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),
        weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
        longDateFormat: {
            LT: 'Ah点mm分',
            LTS: 'Ah点m分s秒',
            L: 'YYYY-MM-DD',
            LL: 'YYYY年MMMD日',
            LLL: 'YYYY年MMMD日Ah点mm分',
            LLLL: 'YYYY年MMMD日ddddAh点mm分',
            l: 'YYYY-MM-DD',
            ll: 'YYYY年MMMD日',
            lll: 'YYYY年MMMD日Ah点mm分',
            llll: 'YYYY年MMMD日ddddAh点mm分'
        },
        meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
        meridiemHour: function(hour, meridiem) {
            if (hour === 12) {
                hour = 0;
            }
            if (meridiem === '凌晨' || meridiem === '早上' ||
                meridiem === '上午') {
                return hour;
            } else if (meridiem === '下午' || meridiem === '晚上') {
                return hour + 12;
            } else {
                // '中午'
                return hour >= 11 ? hour : hour + 12;
            }
        },
        meridiem: function(hour, minute, isLower) {
            var hm = hour * 100 + minute;
            if (hm < 600) {
                return '凌晨';
            } else if (hm < 900) {
                return '早上';
            } else if (hm < 1130) {
                return '上午';
            } else if (hm < 1230) {
                return '中午';
            } else if (hm < 1800) {
                return '下午';
            } else {
                return '晚上';
            }
        },
        calendar: {
            sameDay: function() {
                return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
            },
            nextDay: function() {
                return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
            },
            lastDay: function() {
                return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
            },
            nextWeek: function() {
                var startOfWeek, prefix;
                startOfWeek = moment().startOf('week');
                prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]';
                return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
            },
            lastWeek: function() {
                var startOfWeek, prefix;
                startOfWeek = moment().startOf('week');
                prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]';
                return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
            },
            sameElse: 'LL'
        },
        ordinalParse: /\d{1,2}(日|月|周)/,
        ordinal: function(number, period) {
            switch (period) {
                case 'd':
                case 'D':
                case 'DDD':
                    return number + '日';
                case 'M':
                    return number + '月';
                case 'w':
                case 'W':
                    return number + '周';
                default:
                    return number;
            }
        },
        relativeTime: {
            future: '%s内',
            past: '%s前',
            s: '几秒',
            m: '1 分钟',
            mm: '%d 分钟',
            h: '1 小时',
            hh: '%d 小时',
            d: '1 天',
            dd: '%d 天',
            M: '1 个月',
            MM: '%d 个月',
            y: '1 年',
            yy: '%d 年'
        },
        week: {
            // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
            dow: 1, // Monday is the first day of the week.
            doy: 4 // The week that contains Jan 4th is the first week of the year.
        }
    });
    var importUploader = $scope.importUploader = new FileUploader({
        url: api_bpm_data.impFileData().getRequestedUrl()
    });

    // importUploader.filters.push({
    //     name: 'customFilter',
    //     fn: function(item /*{File|FileLikeObject}*/ , options) {
    //         var type = item.name.slice(item.name.lastIndexOf('.') + 1);
    //         //var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
    //         return (type == 'xlsx');
    //     }
    // });
    importUploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    importUploader.onAfterAddingFile = function(fileItem) {
        console.info('onAfterAddingFile', fileItem);
    };
    importUploader.onAfterAddingAll = function(addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    };

    importUploader.onProgressItem = function(fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    importUploader.onProgressAll = function(progress) {
        console.info('onProgressAll', progress);
    };
    importUploader.onSuccessItem = function(fileItem, response, status, headers) {
        $scope.ldloading.expand_right = false;
        SweetAlert.swal({
            title: "导入成功!",
            confirmButtonColor: "#007AFF",
            type: "success"
        }, function() {
            $scope.scheduleClass = {};
            $scope.calendarView = 'month';
            $scope.calendarDate = moment().startOf('month').toDate();
            $scope.calendarTitle;
            $scope.externalEvents = [];
            api_bpm_schedule.getScheduleClass().then(function(response) {
                if (response.status == 200) {
                    var scheduleClassList = response.list;
                    angular.forEach(scheduleClassList, function(item) {
                        item.startsAt = moment(item.startTime).format('HH:mm:ss');
                        item.endsAt = moment(item.endTime).format('HH:mm:ss');
                        $scope.scheduleClass[item['code']] = item;
                        var templateEvent = {
                            title: item['description'],
                            type: item['code'],
                            startTime: item.startsAt,
                            //starts_at:
                            endTime: item.endsAt,
                            //ends_at:
                            draggable: true
                        };
                        $scope.externalEvents.push(templateEvent);
                    })
                }
            })
        });
        console.info('onSuccessItem', fileItem, response, status, headers);

    };
    importUploader.onErrorItem = function(fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
        SweetAlert.swal({
            title: "系统错误!",
            text: "系统错误，请稍候重试!",
            type: "error"
        });
    };
    importUploader.onCancelItem = function(fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    importUploader.onCompleteItem = function(fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    importUploader.onCompleteAll = function() {
        console.info('onCompleteAll');
    };

    $scope.ldloading = {};
    $scope.import = function() {
        $scope.ldloading.expand_right = true;
        importUploader.onBeforeUploadItem = function(item) {
            console.info('onBeforeUploadItem', item);
        };
        importUploader.uploadAll();
    }

    var filterData = {
        //"userId": loginUser.id,
        "startTime": moment(new Date(y, m, 1, 0, 0)).format('YYYY-MM-DD HH:mm:ss'),
        "endTime": moment(new Date(y, m + 1, 1, 0, 0)).format('YYYY-MM-DD HH:mm:ss')
    };

    var load = $scope.load = function(filterData) {
        api_bpm_schedule.fetchList(filterData.startTime, filterData.endTime, filterData.userId).then(function(response) {
            if (response.status == 200) {
                $scope.events = [];
                console.log(response.list);
                var myData = response.list;
                angular.forEach(myData, function(item) {
                    var eventTemp = {};
                    eventTemp.title = item.description;
                    eventTemp.type = item.scheduleClass.code;
                    eventTemp.startsAt = moment(item.startTime).toDate();
                    eventTemp.endsAtTime = moment(item.endTime).toDate();
                    eventTemp.startTime = item.startTime;
                    eventTemp.endTime = item.endTime;
                    //eventTemp.ends_at = moment(item.endTime).toDate();
                    eventTemp.id = item.id;
                    eventTemp.users = item.users;
                    //               {
                    //     title: '白班',
                    //     type: 'job',
                    //     starts_at: new Date(y, m, 5, 19, 0),
                    //     ends_at: new Date(y, m, 5, 22, 30)
                    // },
                    $scope.events.push(eventTemp);
                })
            }
        });
    }


    $scope.scheduleClass = {};

    $scope.calendarView = 'month';
    $scope.calendarDate = moment().startOf('month').toDate();
    $scope.calendarTitle;
    $scope.externalEvents = [];
    api_bpm_schedule.getScheduleClass().then(function(response) {
        if (response.status == 200) {
            var scheduleClassList = response.list;
            console.log(scheduleClassList)
            angular.forEach(scheduleClassList, function(item) {
                item.startsAt = moment(item.startTime).format('HH:mm:ss');
                item.endsAt = moment(item.endTime).format('HH:mm:ss');
                $scope.scheduleClass[item['code']] = item;
                var templateEvent = {
                    title: item['description'],
                    type: item['code'],
                    startTime: item.startsAt,
                    //starts_at:
                    endTime: item.endsAt,
                    //ends_at:
                    draggable: true
                };
                $scope.externalEvents.push(templateEvent);
            })
        }
    })

    $scope.typeTransfer = function(type) {
        return $scope.scheduleClass[type].name;
    }

    $scope.events = [];
    var acUserSelect = $scope.refreshUser = function(key) {
        //for test                  
        // $scope.users=[{"id":1,"phone":"13971293737","orgId":1,"name":"李静","role":[{"id":1,"rolecode":"admin","role":"主行管理员","flag":0}],"gender":"女","dept":{"id":3,"dept":"运行监控科"},"flag":0,"email":"","account":"005292","nickname":"lijing","group":[{"id":3,"groupName":"运行监控科"}]},{"id":2,"phone":"15807199490","orgId":1,"name":"李进","role":[{"id":1,"rolecode":"admin","role":"主行管理员","flag":0},{"id":7,"rolecode":"change manager","role":"变更流程经理","flag":1},{"id":8,"rolecode":"change coordinator","role":"协调员","flag":0},{"id":9,"rolecode":"configure manager","role":"配置管理员","flag":0},{"id":10,"rolecode":"release manager","role":"发布经理","flag":0}],"gender":"男","dept":{"id":3,"dept":"运行监控科"},"flag":0,"email":"","account":"005298","nickname":"lijin","group":[{"id":3,"groupName":"运行监控科"}]},{"id":3,"phone":"13507195958","orgId":1,"name":"杨代华","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"男","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005241","group":[{"id":9,"groupName":"管理层"}]},{"id":4,"phone":"18717107255","orgId":1,"name":"朱红艳","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"女","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005242","group":[{"id":9,"groupName":"管理层"}]},{"id":5,"phone":"13667282828","orgId":1,"name":"李喆","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"男","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005243","group":[{"id":9,"groupName":"管理层"}]}];
        // return;
        var data = { "idx": "0", "sum": "7", "user": { "roledata": { "rolecode": "watch" } } };
        console.log(data);
        if (key) {
            data.user['name'] = key
        }
        console.log(data);
        api_user_data.fetchDataList('user', data).then(function(response) {
            if (response) {
                if (response.status = 200) {
                    $scope.users = response.list;
                    console.log($scope.users);
                }
            }
        })
    };

    $scope.users = [];
    acUserSelect();


    $scope.calendarView = 'month';
    $scope.calendarDay = new Date();
    $scope.timeLabel = "时间";
    $scope.eventLabel = "描述";

    var judegeEventByLimit = function(event, compareDay) {
        var ret = true;
        angular.forEach($scope.events, function(item) {
            var day = moment(item.startsAt).startOf('day').format('YYYY-MM-DD');
            if (day == compareDay) {
                if (item.type == event.type) {
                    ret = false;
                }
            }
        });
        return ret;
    }
    $scope.eventDropped = function(event, start, end) {
        //console.log("new  eventDropped")
        var externalIndex = $scope.externalEvents.indexOf(event);
        if (externalIndex > -1) {
            if (angular.isDefined(event.users) && event.users != null && event.users.length == 2) {
                var compareDay = moment(start).startOf('day').format('YYYY-MM-DD');
                if (!judegeEventByLimit(event, compareDay)) {
                    SweetAlert.swal({
                        title: "操作失败",
                        text: "同一天只能排出一个白班一个夜班, 请纠正后重试!",
                        type: "error"
                    });
                    return;
                }

                //$scope.externalEvents.splice(externalIndex, 1);

                var bm = moment(moment(start).startOf('day').format('YYYY-MM-DD') + ' ' + event.startTime);
                var em = moment(moment(start).startOf('day').format('YYYY-MM-DD') + ' ' + event.endTime);

                event.startsAt = bm.toDate();
                //console.log(JSON.stringify(event) + "start" + start + " end" + end);
                var endTime = '';
                var startTime = '';
                if (bm.hour() > em.hour()) {
                    endTime = (moment(start).startOf('day').add('day', 1).format('YYYY-MM-DD') + ' ' + event.endTime);
                } else {
                    endTime = (moment(start).startOf('day').format('YYYY-MM-DD') + ' ' + event.endTime);
                }
                startTime = (moment(start).startOf('day').format('YYYY-MM-DD') + ' ' + event.startTime);

                var data = {
                    "scheduleorder": {
                        "description": event.title,
                        "startTime": startTime,
                        "endTime": endTime,
                        "users": event.users,
                        "scheduleClass": { "id": $scope.scheduleClass[event.type].id }
                    }
                };
                //event.endTime = "";
                // event.startTime = "";
                api_bpm_schedule.add(data).then(function(response) {
                    if (response.status == 200) {
                        SweetAlert.swal({
                            title: "操作成功！",
                            text: "新建排班成功!",
                            type: "succes"
                        });
                        var myData = response.data;
                        event.id = myData.id;
                        console.log(JSON.stringify(event));
                        $scope.events.push({ 'id': event.id, 'title': event.title, 'startTime': startTime, 'endTime': endTime, 'users': event.users, 'type': event.type, 'startsAt': event.startsAt, 'draggable': event.draggable });
                    } else {
                        SweetAlert.swal({
                            title: "操作失败",
                            text: "新建排班失败,请稍后重试!",
                            type: "error"
                        })
                    }
                })
            } else {
                SweetAlert.swal({
                    title: "操作失败",
                    text: "请选择值班人",
                    type: "error"
                });
            }
        }
    };



    function showModal(action, event) {
        var modalInstance = $aside.open({
            templateUrl: 'calendarEvent.html',
            placement: 'right',
            size: 'sm',
            backdrop: true,
            controller: function($scope, $modalInstance, scheduleClass, APIService, MementFormat, Alert, EventsData) {
                $scope.$modalInstance = $modalInstance;
                $scope.action = action;
                event.startsAt = moment(event.startsAt).format('YYYY-MM-DD HH:mm:ss');
                event.endsAtTime = moment(event.startsAt).format('YYYY-MM-DD HH:mm:ss');
                $scope.event = event;
                console.log(event);
                $scope.scheduleClassic = scheduleClass;
                $scope.currentDate = MementFormat().toDate();
                $scope.$watch('event.type', function(newvalue, oldvalue) {
                    if (oldvalue == newvalue) return;
                    if (scheduleClass[newvalue]) {
                        var sm = MementFormat(scheduleClass[newvalue].startTime);
                        var em = MementFormat(scheduleClass[newvalue].endTime);
                        event.startsAt = MementFormat(event.startTime).startOf('day').add(sm.hour(), 'hour').add(sm.minute(), 'minute').add(sm.second(), 'second').toDate();
                        event.startTime = MementFormat(event.startTime).startOf('day').add(sm.hour(), 'hour').add(sm.minute(), 'minute').add(sm.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                        event.title = scheduleClass[newvalue].name;
                        if (sm.hour() > em.hour()) {
                            event.endTime = MementFormat(event.startTime).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                            event.endsAtTime = MementFormat(event.startTime).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        } else {
                            event.endTime = MementFormat(event.startTime).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                            event.endsAtTime = MementFormat(event.startTime).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        }

                    }
                });

                $scope.$watch('event.startsAt', function(newvalue, oldvalue) {
                    if (oldvalue == newvalue) return;
                    if (MementFormat(oldvalue).format('YYYY-MM-DD HH:mm:ss') == MementFormat(newvalue).format('YYYY-MM-DD HH:mm:ss')) return;
                    if (scheduleClass[event.type]) {
                        var sm = MementFormat(scheduleClass[event.type].startTime);
                        var em = MementFormat(scheduleClass[event.type].endTime);
                        //event.starts_at = MementFormat(event.starts_at).startOf('day').add(sm.hour(),'hour').add(sm.minute(),'minute').add(sm.second(),'second').toDate();
                        if (sm.hour() > em.hour()) {
                            event.endTime = MementFormat(event.startsAt).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                            event.endsAtTime = MementFormat(event.startsAt).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        } else {
                            event.endTime = MementFormat(event.startsAt).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                            event.endsAtTime = MementFormat(event.startsAt).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        }
                    }
                });
                $scope.setEndOpen = function() {
                    if (scheduleClass[event.type]) {
                        var sm = MementFormat(scheduleClass[event.type].startTime);
                        var em = MementFormat(scheduleClass[event.type].endTime);
                        event.startsAt = MementFormat(event.startTime).startOf('day').add(sm.hour(), 'hour').add(sm.minute(), 'minute').add(sm.second(), 'second').toDate();
                        if (sm.hour() > em.hour()) {
                            event.endTime = MementFormat(event.startTime).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                            event.endsAtTime = MementFormat(event.startTime).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        } else {
                            event.endTime = MementFormat(event.startTime).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
                            event.endsAtTime = MementFormat(event.startTime).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
                        }
                    }
                }

                //同一天只能排出一个白班一个夜班
                function judegeEventByLimit(event) {
                    var ret = true;
                    var compareDay = moment(event.startsAt).startOf('day').format('YYYY-MM-DD');
                    angular.forEach(EventsData, function(item) {
                        var day = moment(item.startsAt).startOf('day').format('YYYY-MM-DD');
                        if (day == compareDay) {
                            if (angular.isDefined(event.id)) {
                                if (item.type == event.type && event.id != item.id) ret = false;
                            } else {
                                if (item.type == event.type) ret = false;
                            }
                        }
                    });
                    return ret;
                }

                $scope.ok = function(event) {
                    // console.log("event="+JSON.stringify(event));

                    if (angular.isDefined(event.users) && event.users != null && event.users.length == 2) {
                        if (judegeEventByLimit(event)) {
                            event.action = action;
                            $modalInstance.close(event);
                        } else {
                            Alert.swal({
                                title: "操作失败",
                                text: "同一天只能排出一个白班一个夜班, 请纠正后重试!",
                                type: "error"
                            })
                        }
                    } else {
                        Alert.swal({
                            title: "操作失败",
                            text: "请填写值班人",
                            type: "error"
                        })
                    }
                };
                $scope.deleteEvent = function(event) {
                    event.action = "Deleted";
                    $modalInstance.close(event);
                };

                $scope.refreshModalUser = function(key) {
                    //for test                  
                    // $scope.users=[{"id":1,"phone":"13971293737","orgId":1,"name":"李静","role":[{"id":1,"rolecode":"admin","role":"主行管理员","flag":0}],"gender":"女","dept":{"id":3,"dept":"运行监控科"},"flag":0,"email":"","account":"005292","nickname":"lijing","group":[{"id":3,"groupName":"运行监控科"}]},{"id":2,"phone":"15807199490","orgId":1,"name":"李进","role":[{"id":1,"rolecode":"admin","role":"主行管理员","flag":0},{"id":7,"rolecode":"change manager","role":"变更流程经理","flag":1},{"id":8,"rolecode":"change coordinator","role":"协调员","flag":0},{"id":9,"rolecode":"configure manager","role":"配置管理员","flag":0},{"id":10,"rolecode":"release manager","role":"发布经理","flag":0}],"gender":"男","dept":{"id":3,"dept":"运行监控科"},"flag":0,"email":"","account":"005298","nickname":"lijin","group":[{"id":3,"groupName":"运行监控科"}]},{"id":3,"phone":"13507195958","orgId":1,"name":"杨代华","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"男","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005241","group":[{"id":9,"groupName":"管理层"}]},{"id":4,"phone":"18717107255","orgId":1,"name":"朱红艳","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"女","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005242","group":[{"id":9,"groupName":"管理层"}]},{"id":5,"phone":"13667282828","orgId":1,"name":"李喆","role":[{"id":2,"rolecode":"user","role":"主行员工","flag":1}],"gender":"男","dept":{"id":9,"dept":"管理层"},"flag":0,"email":"","account":"005243","group":[{"id":9,"groupName":"管理层"}]}];
                    // return;
                    var data = { "idx": "0", "sum": "7", "user": { "roledata": { "rolecode": "watch" } } };
                    if (key) {
                        data.user['name'] = key
                    }
                    console.log(data);
                    APIService.fetchDataList('user', data).then(function(response) {
                        if (response) {
                            console.log("response=" + JSON.stringify(response))
                            if (response.status = 200) {
                                $scope.modalusers = response.list;
                                console.log($scope.users);
                            }
                        }
                    })
                };

                $scope.users = [];
                $scope.refreshModalUser();
            },
            resolve: {
                scheduleClass: function() {
                    return $scope.scheduleClass;
                },
                APIService: function() {
                    return api_user_data;
                },
                MementFormat: function() {
                    return moment;
                },
                Alert: function() {
                    return SweetAlert;
                },
                EventsData: function() {
                    return $scope.events;
                }
            }
        });
        modalInstance.result.then(function(selectedEvent) {
            if (selectedEvent.action == 'Edited') {
                //new
                var data = {
                    "scheduleorder": {
                        "description": selectedEvent.title,
                        "startTime": selectedEvent.startTime,
                        "endTime": selectedEvent.endTime,
                        "users": selectedEvent.users,
                        "scheduleClass": { "id": $scope.scheduleClass[selectedEvent.type].id }
                    }
                };
                api_bpm_schedule.add(data).then(function(response) {
                    if (response.status == 200) {
                        SweetAlert.swal({
                            title: "操作成功！",
                            text: "新建排班成功!",
                            type: "succes"
                        });

                        $scope.events.push(convertEvent(response.data));
                        // angular.forEach($scope.events,function(item){
                        //     if(item.id==selectedEvent.id){
                        //         item = selectedEvent;
                        //     }
                        // })
                    } else {
                        SweetAlert.swal({
                            title: "操作失败",
                            text: "新建排班失败,请稍后重试!",
                            type: "error"
                        })
                    }
                })
            } else if (selectedEvent.action == 'Clicked') {
                var data = {
                    "scheduleorder": {
                        "id": selectedEvent.id,
                        "description": selectedEvent.title,
                        "startTime": selectedEvent.startTime,
                        "endTime": selectedEvent.endTime,
                        "users": selectedEvent.users,
                        "scheduleClass": { "id": $scope.scheduleClass[selectedEvent.type].id }
                    }
                };
                api_bpm_schedule.update(data).then(function(response) {
                    if (response.status == 200) {
                        SweetAlert.swal({
                            title: "操作成功！",
                            text: "排班更新成功!",
                            type: "succes"
                        });
                        angular.forEach($scope.events, function(item) {
                            if (item.id == selectedEvent.id) {
                                item = selectedEvent;
                            }
                        })
                    } else {
                        SweetAlert.swal({
                            title: "操作失败",
                            text: "排班更新失败,请稍后重试!",
                            type: "error"
                        })
                    }
                })
            } else {
                $scope.eventDeleted(selectedEvent);
            }
        });
    }

    $scope.moment = function(string) {
        return moment(string);
    }


    $scope.eventClicked = function(event) {
        showModal('Clicked', event);
    };


    $scope.addEvent = function() {
        var sm = moment($scope.scheduleClass['job'].startTime);
        var em = moment($scope.scheduleClass['job'].endTime);

        var newevent = {
            title: $scope.scheduleClass['job'].name,
            type: $scope.scheduleClass['job'].code,
            user: loginUser
        };


        newevent.startsAt = moment($scope.calendarDay).startOf('day').add(sm.hour(), 'hour').add(sm.minute(), 'minute').add(sm.second(), 'second').toDate();
        newevent.startTime = moment($scope.calendarDay).startOf('day').add(sm.hour(), 'hour').add(sm.minute(), 'minute').add(sm.second(), 'second').format('YYYY-MM-DD HH:mm:ss');

        if (sm.hour() > em.hour()) {
            newevent.endTime = moment($scope.calendarDay).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
            newevent.endsAtTime = moment($scope.calendarDay).startOf('day').add(1, 'day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
            //newevent.ends_at = moment($scope.calendarDay).startOf('day').add(1, 'day').add(em.hour(),'hour').add(em.minute(),'minute').add(em.second(),'second').toDate();
        } else {
            newevent.endTime = moment($scope.calendarDay).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').format('YYYY-MM-DD HH:mm:ss');
            newevent.endsAtTime = moment($scope.calendarDay).startOf('day').add(em.hour(), 'hour').add(em.minute(), 'minute').add(em.second(), 'second').toDate();
            //newevent.ends_at = moment($scope.calendarDay).startOf('day').add(em.hour(),'hour').add(em.minute(),'minute').add(em.second(),'second').toDate();    
        }
        $scope.eventEdited(newevent);
    };

    $scope.eventEdited = function(event) {
        showModal('Edited', event);
    };

    $scope.eventDeleted = function(event) {
        SweetAlert.swal({
            title: "确认删除?",
            text: "删除的数据不可恢复，请确认继续操作!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "继续删除",
            cancelButtonText: "取消操作",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function(isConfirm) {
            if (isConfirm) {
                api_bpm_schedule.remove([event.id]).then(function(response) {
                    if (response.status == 200) {
                        $scope.events.splice(event.$id, 1);
                        SweetAlert.swal("操作成功!", "数据已经被删除.", "success");
                    } else {
                        SweetAlert.swal("操作失败!", "数据暂时无法被删除,请稍候重试", "error");
                    }
                });
            } else {
                SweetAlert.swal("操作取消", "数据安全", "error");
            }
        });
    };

    //$scope.timeStart;
    //$scope.timeEnd;
    var updateView = function(newvalue, oldvalue) {
        if (oldvalue == newvalue) return;
        if (moment(oldvalue).format('YYYY-MM-DD HH:mm:ss') == moment(newvalue).format('YYYY-MM-DD HH:mm:ss')) return;
        var timeStart, timeEnd, timeStartSpan, timeEndSpan;

        if ($scope.calendarView == "year") {

        } else if ($scope.calendarView == "month") {
            timeStart = moment(newvalue).startOf('month');
            timeEnd = moment(newvalue).endOf('month');
        } else if ($scope.calendarView == "week") {
            timeStart = moment(newvalue).startOf('week');
            timeEnd = moment(newvalue).endOf('week');

        } else if ($scope.calendarView == "Day") {
            timeStart = moment(newvalue).startOf('day');
            timeEnd = moment(newvalue).endOf('day');
        }
        timeStartSpan = timeStart.format('YYYY-MM-DD HH:mm:ss');
        timeEndSpan = timeEnd.format('YYYY-MM-DD HH:mm:ss');
        filterData["startTime"] = timeStartSpan;
        filterData["endTime"] = timeEndSpan;
        load(filterData);
    }

    $scope.$watch('calendarDate', updateView)


    $scope.next = function() {
        $scope.calendarControl.next();
    }

    $scope.prev = function() {
        $scope.calendarControl.prev();
    }

    $scope.setCalendarToToday = function() {
        $scope.calendarDay = new Date();
    };

    $scope.toggle = function($event, field, event) {
        $event.preventDefault();
        $event.stopPropagation();

        event[field] = !event[field];
    };

    $scope.load(filterData);

}]);

// "$rootScope","$scope", "$state", "$timeout", "$interval", "SweetAlert", "i18nService", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_bpm_schedule", "$aside", "moment"
app.controller('shiftScheduleCtrl', ["$rootScope", "$scope", "$state", "$timeout", "$interval", "moment", "SweetAlert", "Restangular", "api_bpm_schedule", "api_user_data", function($rootScope, $scope, $state, $timeout, $interval, moment, SweetAlert, Restangular, api_bpm_schedule, api_user_data) {
    var loginUser = $rootScope.user;
    $scope.shiftes = [];
    var load = function() {
        $scope.shiftes = [];
        api_bpm_schedule.queryHandleoutSwitch(loginUser.id).then(function(response) {
            if (response) {
                var myData = Restangular.stripRestangular(response);
                angular.forEach(myData.list, function(item) {
                    $scope.shiftes.push(item);
                })
            }
        })
    }

    $scope.getShiftType = function(shift) {
        var ret = "error";
        if (shift.scheduleOrderDTO.status.id == 2) {
            ret = "import";
        }
        if (shift.scheduleOrderDTO.status.id == 4) {
            ret = "upload";
        }
        return ret;
    }

    // var getShift = function(){
    //     angular.forEach($scope.shiftes, function(item){
    //         if(item.user.id==loginUser.id){
    //             return item;
    //         }
    //     })
    // }
    var getShift = function() {
        var ret = null;
        angular.forEach($scope.shiftes, function(item) {
            if (item.user.id == loginUser.id && (item.status.id == 1 || item.status.id == 2) && ret == null) {
                ret = item;
            }
        })
        return ret;
    }

    $scope.getHandle = function() {
        var ret = "error";
        var shift;
        var index = 0;
        //angular.forEach($scope.shiftes, function(item){
        for (var index1 in $scope.shiftes) {
            //shift = item;
            var item = $scope.shiftes[index1];
            //console.log(item.user.id +"==" +loginUser.id + "shift.status.id"+shift.status.id + " " + shift.scheduleOrderDTO.status.id );
            if (item.user.id == loginUser.id) {
                shift = item;
                //console.log(shift.status.id);
                if (shift.status.id == 1) {
                    //console.log("shift.scheduleOrderDTO.status.id="+shift.scheduleOrderDTO.status.id);
                    if (shift.scheduleOrderDTO.status.id == 2) {
                        ret = "import";
                    }
                } else if (shift.status.id == 2) {
                    if (shift.scheduleOrderDTO.status.id == 4) {
                        ret = "upload";
                        break;
                        //return;
                    }
                }
                //return ret;
            }
            if (item.status.id == 5) {
                index++;
            }
            //});
        }
        //console.log(index)
        if (ret == 'import' && index != 2) {
            ret = 'uploadDes';
        }
        console.log(ret);
        return ret;
    }

    $scope.importShift = function() {
        var shift = getShift();
        var data = {};
        if (shift.status.id == 1) {
            data.status = {};
            data.status.id = 4;
        }
        data.id = shift.id;
        api_bpm_schedule.handleSchedule(data).then(function(response) {
            if (response) {
                var myData = Restangular.stripRestangular(response);
                if (response.status == 200) {
                    SweetAlert.swal("接班成功!", "接班成功！", "success");
                    load();
                } else {
                    SweetAlert.swal("接班失败!", "接班失败,请稍候重试", "error");
                }
            }
        })
    }

    $scope.uploadShift = function() {
        var shift = getShift();
        var data = {};
        if (shift.status.id == 2) {
            data.status = {};
            data.status.id = 5;
        }
        data.id = shift.id;
        api_bpm_schedule.handleSchedule(data).then(function(response) {
            if (response) {
                var myData = Restangular.stripRestangular(response);
                if (response.status == 200) {
                    SweetAlert.swal("交班成功!", "交班成功！", "success");
                    load();
                } else {
                    SweetAlert.swal("交班失败!", "交班失败,请稍候重试", "error");
                }
            }
        })
    }

    load();

    // api_bpm_schedule.queryRecieveSwitch(loginUser.id).then(function(response){
    //     if(response){
    //         var myData = Restangular.stripRestangular(response);
    //         angular.forEach(myData.list, function(item){
    //             $scope.shiftes.push(item);
    //         })
    //     }
    // })
}]);

app.controller('shiftRecordCtrl', ["$rootScope", "$scope", "$state", "$timeout", "$interval", "SweetAlert", "i18nService", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_bpm_schedule", "$aside", "moment", function($rootScope, $scope, $state, $timeout, $interval, SweetAlert, i18nService, uiGridConstants, uiGridGroupingConstants, Restangular, api_bpm_schedule, $aside, moment) {
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    i18nService.setCurrentLang($scope.lang);

    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = false;
    $scope.gridOptions.enableGridMenu = true;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = false;
    $scope.gridOptions.fastWatch = true;
    $scope.gridOptions.useExternalFiltering = true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = false;

    //$scope.gridOptions.rowTemplate = "<div ng-dblclick=\"grid.appScope.pdList.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";
    //
    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };

    $scope.gridOptions.columnDefs = [{
            name: 'orderTime',
            displayName: '日期',
            width: 100
        }, {
            name: 'scheduleClass.name',
            displayName: '班次',
            width: 80,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[2].user.name',
            displayName: '第一交班人',
            width: 100,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[2].shiftTime',
            displayName: '交班时间',
            width: 180,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[3].user.name',
            displayName: '第二交班人',
            width: 100,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[3].shiftTime',
            displayName: '交班时间',
            width: 180,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[0].user.name',
            displayName: '第一接班人',
            width: 100,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[0].succeedTime',
            displayName: '接班时间',
            width: 180,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[1].user.name',
            displayName: '第二接班人',
            width: 100,
            enableFiltering: false
        },
        {
            name: 'scheduleWatchList[1].succeedTime',
            displayName: '接班时间',
            width: 180,
            enableFiltering: false
        },
        {
            name: 'status.name',
            displayName: '状态',
            width: 100,
            enableFiltering: false
        }
    ];



    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            console.log(newPage);
            console.log(pageSize);
            $scope.refreshData('expand-right', {
                "idx": newPage - 1,
                "sum": pageSize
            });
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
            //$scope.selected.item = data.entity;
            console.log(data);
        });
        //     gridApi.core.on.filterChanged($scope, function() {
        //   var grid = this.grid;
        //   var filtersData = {
        //     idx:0,
        //     sum:10
        //   };
        //   angular.forEach(grid.columns,function(item){
        //     if(item.enableFiltering){
        //       if(angular.isDefined(item.filters[0].term)&&item.filters[0].term!=''){
        //         // console.log('item.filters[0]='+JSON.stringify(item.filters[0]));
        //         if(angular.isUndefined(filtersData['scheduling'])){
        //           filtersData['scheduling']={};
        //         }
        //         filtersData['scheduling'][item.field]=item.filters[0].term;
        //       }                                                
        //     }
        //   });
        //   $scope.memoryfilterData = filtersData;
        //   $scope.refreshData('expand-right', filtersData);
        // });
    };


    this.selectRowFunction = function(data) {
        console.log(data);
        //    $state.go('app.process.modeler',{modelId:data.id});
        $state.go('app.scheduling.editor', {
            taskId: data.taskId,
            processInstanceId: data.processInstanceId
        });
    };
    $scope.search = function(start, end) {
        var filtersData = {
            "scheduleorder": { "type": "4" },
            idx: 0,
            sum: 10
        };
        if (angular.isDefined(start) || angular.isDefined(end)) {
            filtersData.scheduleorder['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
            // filtersData.scheduleorder['endTime']=moment(end).format('YYYY-MM-DD HH:mm:ss');
            var timedata = new Date(end).getTime() + 86400000;
            var d = new Date(timedata)
            filtersData.scheduleorder['endTime'] = moment(d).format('YYYY-MM-DD HH:mm:ss');
            console.log(timedata)
        }
        $scope.memoryfilterData = filtersData;
        $scope.refresh('expand-right', filtersData);
    }
    $scope.ldloading = false;
    $scope.export = function(start, end) {
        $scope.ldloading.expand_right = true;
        var filtersData = {
            scheduleorder: { "type": "4" },
            idx: 0,
            sum: 1000
        };
        if (angular.isDefined(start) || angular.isDefined(end)) {
            filtersData.scheduleorder['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
            var timedata = new Date(end).getTime() + 86400000;
            var d = new Date(timedata)
            filtersData.scheduleorder['endTime'] = moment(d).format('YYYY-MM-DD HH:mm:ss');
        }
        // if(angular.isDefined($scope.ciclassify)&&$scope.ciclassify!=null){
        //     if(angular.isUndefined($scope.ciclassify.children)||$scope.ciclassify.children.length==0){
        api_bpm_schedule.query(filtersData).then(function(data) {
                var dataList = Restangular.stripRestangular(data).list;
                // if(dataList&&(dataList.list.length>=1)){
                var headers = [];
                var fieldHeaders = [];
                var exportdata = [];
                var fields = [];
                var rowData = [];
                var rowdata = [];
                if ($scope.gridOptions.columnDefs.length > 0) {
                    angular.forEach($scope.gridOptions.columnDefs, function(prop) {
                        headers.push(prop.displayName);
                        // angular.forEach(prop.form.fields, function(field, index){
                        //     fieldHeaders.push(field.templateOptions.label);
                        //     fields.push(field.key);
                        //     if(index!=0){
                        //         headers.push("");
                        //     }                           
                        // });             
                    })
                }
                var rowLine = [];
                var dataline = [];
                for (var i = 0; i < dataList.length; i++) {
                    if (angular.isUndefined(dataList[i].scheduleWatchList[0])) { dataList[i].scheduleWatchList[0] = {} }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[1])) { dataList[i].scheduleWatchList[1] = {} }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[2])) { dataList[i].scheduleWatchList[2] = {} }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[3])) { dataList[i].scheduleWatchList[3] = {} }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[2].user)) { dataList[i].scheduleWatchList[2].user = "" }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[2].shiftTime)) { dataList[i].scheduleWatchList[2].shiftTime = "" }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[1].user)) { dataList[i].scheduleWatchList[1].user = "" }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[1].succeedTime)) { dataList[i].scheduleWatchList[1].succeedTime = "" }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[0].user)) { dataList[i].scheduleWatchList[0].user = "" }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[0].succeedTime)) { dataList[i].scheduleWatchList[0].succeedTime = "" }

                    if (angular.isUndefined(dataList[i].scheduleWatchList[3].user)) { dataList[i].scheduleWatchList[3].user = "" }
                    if (angular.isUndefined(dataList[i].scheduleWatchList[3].shiftTime)) { dataList[i].scheduleWatchList[3].shiftTime = "" }
                    exportdata = {
                        orderTime: dataList[i].orderTime,
                        scheduleClass: dataList[i].scheduleClass.name,
                        username2: dataList[i].scheduleWatchList[2].user.name,
                        shiftTime2: dataList[i].scheduleWatchList[2].shiftTime,
                        username3: dataList[i].scheduleWatchList[3].user.name,
                        succeedTime3: dataList[i].scheduleWatchList[3].shiftTime,
                        username0: dataList[i].scheduleWatchList[0].user.name,
                        succeedTime0: dataList[i].scheduleWatchList[0].succeedTime,
                        username1: dataList[i].scheduleWatchList[1].user.name,
                        shiftTime1: dataList[i].scheduleWatchList[1].succeedTime,
                        status: dataList[i].status.name
                    }

                    // dataline.push([exportdata]);
                    var rowLine = [];
                    angular.forEach(exportdata, function(keyfield) {
                        // angular.forEach(data,function(keyfield){
                        //     if(data[keyfield]){ 
                        rowLine.push(keyfield);
                        //     }else{
                        //         rowLine.push("");
                        //     }
                        // })
                        // rowData.push(rowLine);
                    })
                    rowData.push(rowLine);
                    rowdata = rowData;
                }


                var csvdata = headers.join(',') + '\r\n';
                // csvdata = csvdata + fieldHeaders.join(',') + '\r\n';
                // csvdata = csvdata + fields.join(',') + '\r\n';
                angular.forEach(rowData, function(line) {
                    csvdata = csvdata + line.join(',') + '\r\n';
                })
                csvdata = "\ufeff" + csvdata;

                var file = new Blob([csvdata], {
                    type: 'application/csv;charset=utf-8'
                });
                // var filename = $scope.ciclassify.label;
                var fileURL = URL.createObjectURL(file);
                var a = document.createElement('a');
                a.href = fileURL;
                a.target = '_blank';
                a.download = "交接班记录" + '.csv';
                document.body.appendChild(a);
                a.click();
                // }
                $scope.ldloading.expand_right = false;
                // },function(){
                //  $scope.ldloading.expand_right = false;
            })
            //     }else{
            //         SweetAlert.swal({
            //                 title: "参数不合法!",
            //                 text: "参数不合法，请选择没有子类的配置项导出!",
            //                 type: "error"
            //             });
            //     }
            // }else{
            //     SweetAlert.swal({
            //         title: "参数不合法!",
            //         text: "参数不合法，请选择需要导出的配置项分类!",
            //         type: "error"
            //     });
            // }
    }


    $scope.today = function() {
        $scope.dt = new Date();
    };
    $scope.today();

    $scope.clear = function() {
        $scope.dt = null;
    };

    // Disable weekend selection
    $scope.disabled = function(date, mode) {
        return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
    };

    // $scope.toggleMin = function () {
    //     $scope.minDate = $scope.minDate ? null : new Date();
    // };
    // $scope.toggleMin();

    $scope.open = function($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = !$scope.opened;
    };
    $scope.endOpen = function($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.startOpened = false;
        $scope.endOpened = !$scope.endOpened;
    };
    $scope.startOpen = function($event) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.endOpened = false;
        $scope.startOpened = !$scope.startOpened;
    };

    $scope.dateOptions = {
        formatYear: 'yy',
        startingDay: 1
    };

    $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    $scope.format = $scope.formats[1];

    $scope.hstep = 1;
    $scope.mstep = 15;

    // Time Picker
    $scope.options = {
        hstep: [1, 2, 3],
        mstep: [1, 5, 10, 15, 25, 30]
    };

    $scope.ismeridian = true;
    $scope.toggleMode = function() {
        $scope.ismeridian = !$scope.ismeridian;
    };

    $scope.update = function() {
        var d = new Date();
        d.setHours(14);
        d.setMinutes(0);
        $scope.dt = d;
    };

    $scope.changed = function() {
        $log.log('Time changed to: ' + $scope.dt);
    };

    $scope.clear = function() {
        $scope.dt = null;
    };

    var defaultFilterData = {
        "idx": 0,
        "sum": 10
    };

    $scope.ldloading = {};

    $scope.refreshData = function(style, filterData) {
        // $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            filterData['searchType'] = $scope.searchTypes;
        }
        $scope.myData = [];

        api_bpm_schedule.querySwitch(filterData).then(function(data) {
            var myData = Restangular.stripRestangular(data);
            $scope.gridOptions.totalItems = myData.totalNum;
            $scope.myData = myData.list;
            // $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            // $scope.ldloading[style.replace('-', '_')] = false;
        });
    };

    $scope.refreshData('expand-right', defaultFilterData);
    $scope.refresh = function(style, filterData) {
        // $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            filterData['searchType'] = $scope.searchTypes;
        }
        $scope.myData = [];

        api_bpm_schedule.query(filterData).then(function(data) {
            var myData = Restangular.stripRestangular(data);
            $scope.gridOptions.totalItems = myData.totalNum;
            $scope.myData = myData.list;
            // $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            // $scope.ldloading[style.replace('-', '_')] = false;
        });
    };
}]);
// delete-event-html="'<i class=\'glyphicon glyphicon-remove\'></i>'"
// edit-event-html="'<i class=\'glyphicon glyphicon-pencil\'></i>'"